#include <jni.h>
#include <stdio.h>
#include "com_buddy_jni_demo05_JNIPrimitiveArray.h"

//在Java中，array是指一种类型，类似于类。
//一共有9种java的array，8个基本类型的array和一个object的array。
//JNI针对java的基本类型都定义了相应的array：
//  jintArray, jbyteArray, jshortArray, jlongArray, jfloatArray, jdoubleArray, jcharArray, jbooleanArray，并且也有面向object的jobjectArray。
//需要在JNI array和Native array之间进行转换
JNIEXPORT jdoubleArray JNICALL Java_com_buddy_jni_demo05_JNIPrimitiveArray_sumAndAverage
    (JNIEnv *env, jobject thisObj, jintArray inJNIArray) {
        // Step 1: Convert the incoming JNI jintarray to C's jint[]
        jint *inCArray = (*env)->GetIntArrayElements(env, inJNIArray, NULL);
        if (NULL == inCArray) return NULL;
        jsize length = (*env)->GetArrayLength(env, inJNIArray);

        // Step 2: Perform its intended operations
        jint sum = 0;
        int i;
        for (i = 0; i < length; i++) {
           sum += inCArray[i];
        }
        jdouble average = (jdouble)sum / length;
        (*env)->ReleaseIntArrayElements(env, inJNIArray, inCArray, 0); // release resources

        jdouble outCArray[] = {sum, average};

        // Step 3: Convert the C's Native jdouble[] to JNI jdoublearray, and return
        jdoubleArray outJNIArray = (*env)->NewDoubleArray(env, 2);  // allocate
        if (NULL == outJNIArray) return NULL;
        (*env)->SetDoubleArrayRegion(env, outJNIArray, 0 , 2, outCArray);  // copy
        return outJNIArray;
}

